package ru.spies.forms;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public abstract class FormCreator {
		
	private String cookieName=null;
	
	protected static final String SOME_ERRORS="<p>Данный раздел недоступен! :(</p><p>Простите за временные неудобства...<p><input onclick=\"goHome()\" type=\"button\" class=\"inFormBtn\" value=\"На главную\">";
	
	protected static final String SHOW_RESULT_LINK="showResult.jsp";
	
	protected String createForm(String content){
		StringBuffer htmlForm = new StringBuffer("<div class=\"allForm\">");
		htmlForm.append("<div class=\"formTopAndBot\"></div>");
		htmlForm.append("<form class=\"formSystem\"><div class=\"inForm\">");
		htmlForm.append(content);
		htmlForm.append("</div></form>");		
		htmlForm.append("<div class=\"formTopAndBot\"></div>");
		htmlForm.append("</div>");
		return htmlForm.toString();
	}
	
	protected String createFormWithPostMethod(String content,String linkForGet){
		StringBuffer htmlForm = new StringBuffer("<div class=\"allForm\">");
		htmlForm.append("<div class=\"formTopAndBot\"></div>");
		htmlForm.append("<form class=\"formSystem\" method=\"post\"");
		htmlForm.append( " action=\""+linkForGet+"\" accept-charset=\"utf-8\"><div class=\"inForm\">");		
		htmlForm.append(content);
		htmlForm.append("</div></form>");		
		htmlForm.append("<div class=\"formTopAndBot\"></div>");
		htmlForm.append("</div>");
		return htmlForm.toString();
	}
					
	protected ICookie readCookie(HttpServletRequest request){
		Cookie cookies[] = request.getCookies();
		if (cookies==null){
			return null;
		}
		for(Cookie i:cookies){
			if (i.getName().equals(cookieName)){
				return childCookieWork(i);
			}
		}
		return null;
	}
		
	protected abstract ICookie childCookieWork(Cookie cookie);

	protected void setCookieName(String cookieName) {
		this.cookieName = cookieName;
	}
	
	public abstract String createThisForm();
	
	public String chooseFunctionForWork(HttpServletRequest request){
		ICookie cookVal=readCookie(request);
		if (cookVal==null) return createForm(SOME_ERRORS);
		return workWithCookieValue(cookVal);
	}
	
	protected abstract String workWithCookieValue(ICookie cook);
				
}
